import Router from '@koa/router';
import { upload } from '../utils/upload';
import { Context } from 'koa';
import { UploadModel } from '../models/upload.model';
import path from 'path';

const router = new Router();

// 单文件上传
router.post('/single', async (ctx: Context) => {
  try {
    await upload.single('file')(ctx, async () => {});

    const file = (ctx.request as any).file;
    if (!file) {
      ctx.status = 400;
      ctx.body = {
        success: false,
        message: '没有上传文件',
      };
      return;
    }

    // 保存文件信息到数据库
    const fileInfo = {
      filename: file.filename,
      originalname: file.originalname,
      mimetype: file.mimetype,
      size: file.size,
      path: path.join('uploads', file.filename),
    };

    const fileId = await UploadModel.create(fileInfo);

    ctx.body = {
      success: true,
      message: '文件上传成功',
      data: {
        id: fileId,
        ...fileInfo,
      },
    };
  } catch (error) {
    console.error('文件上传错误:', error);
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: '文件上传失败',
      error: error instanceof Error ? error.message : '未知错误',
    };
  }
});

// 多文件上传
router.post('/multiple', async (ctx: Context) => {
  try {
    await upload.array('files', 5)(ctx, async () => {});

    const files = (ctx.request as any).files;
    if (!files || !Array.isArray(files) || files.length === 0) {
      ctx.status = 400;
      ctx.body = {
        success: false,
        message: '没有上传文件',
      };
      return;
    }

    // 保存所有文件信息到数据库
    const fileInfos = await Promise.all(
      files.map(async (file) => {
        const fileInfo = {
          filename: file.filename,
          originalname: file.originalname,
          mimetype: file.mimetype,
          size: file.size,
          path: path.join('uploads', file.filename),
        };
        const fileId = await UploadModel.create(fileInfo);
        return {
          id: fileId,
          ...fileInfo,
        };
      }),
    );

    ctx.body = {
      success: true,
      message: '文件上传成功',
      data: fileInfos,
    };
  } catch (error) {
    console.error('文件上传错误:', error);
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: '文件上传失败',
      error: error instanceof Error ? error.message : '未知错误',
    };
  }
});

// 获取所有文件列表
router.get('/files', async (ctx: Context) => {
  try {
    const files = await UploadModel.findAll();
    ctx.body = {
      success: true,
      data: files,
    };
  } catch (error) {
    console.error('获取文件列表错误:', error);
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: '获取文件列表失败',
      error: error instanceof Error ? error.message : '未知错误',
    };
  }
});

// 获取单个文件信息
router.get('/files/:id', async (ctx: Context) => {
  try {
    const id = parseInt(ctx.params.id);
    const file = await UploadModel.findById(id);
    if (!file) {
      ctx.status = 404;
      ctx.body = {
        success: false,
        message: '文件不存在',
      };
      return;
    }
    ctx.body = {
      success: true,
      data: file,
    };
  } catch (error) {
    console.error('获取文件信息错误:', error);
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: '获取文件信息失败',
      error: error instanceof Error ? error.message : '未知错误',
    };
  }
});

// 删除文件
router.delete('/files/:id', async (ctx: Context) => {
  try {
    const id = parseInt(ctx.params.id);
    const file = await UploadModel.findById(id);
    if (!file) {
      ctx.status = 404;
      ctx.body = {
        success: false,
        message: '文件不存在',
      };
      return;
    }

    // 删除数据库记录
    const deleted = await UploadModel.delete(id);
    if (!deleted) {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: '删除文件失败',
      };
      return;
    }

    ctx.body = {
      success: true,
      message: '文件删除成功',
    };
  } catch (error) {
    console.error('删除文件错误:', error);
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: '删除文件失败',
      error: error instanceof Error ? error.message : '未知错误',
    };
  }
});

export const uploadRoutes = router;
